package com.hdl.commons;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpRequest;

/**
 * <pre>
 * TODO : 阿里云市场提供的新闻
 * - 全国热门带正文新闻查询_易源数据
 * - https://market.aliyun.com/products/57126001/cmapi011150.html?spm=5176.11065268.1996646101.searchclickresult.55a695e67EHRm1#sku=yuncode515000003
 * - 依赖： Hutools slf4j FastJSON
 * ClassName : com.teach.commons.NewsByAliyun
 * Author : J.L.Zhou
 * Date : 2020-07-02 10:40
 * Version : V1.0
 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes
 * </pre>
 */
public class NewsByAliyun {

	private static Logger log = LoggerFactory.getLogger(NewsByAliyun.class);

	private static NewsByAliyun spider = new NewsByAliyun();

	private NewsByAliyun() {
	}

	public static NewsByAliyun getInstance() {
		return spider;
	}

	private String appCode = "7e57b10e30b84d75a417f1c9d2ee04d3";

	public void setAppCode(String appCode) {
		log.debug("设置了appCode={}", appCode);
		this.appCode = appCode;
	}

	/**
	 * - 读取所有的新闻类别（频道）
	 * @return
	 */
	public List<NewsClass> listNewsClass() {
		String url = "http://ali-news.showapi.com/channelList";
		String body = HttpRequest
				.get(url)
				.header("Authorization", "APPCODE " + appCode)
				.execute().body();
		log.debug(body);
		JSONObject obj = JSONObject.parseObject(body);
		if(obj.getIntValue("showapi_res_code")==0) {
			return obj.getJSONObject("showapi_res_body").getJSONArray("channelList").toJavaList(NewsClass.class);
		}else {
			String msg = obj.getString("showapi_res_error");
			log.warn(msg);
			throw new RuntimeException(msg);
		}
	}
	
	/**
	 * - 读取新闻
	 * @param channelId - 新闻频道编号,""标识方法所有频道
	 * @param rowMax - 返回数量
	 * @param page - 页码
	 * @return
	 */
	public List<News> listNews(String channelId,int rowMax,int page){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<News> list = new ArrayList<NewsByAliyun.News>();
		String url = "http://ali-news.showapi.com/newsList";
		String body = HttpRequest
				.get(url)
				.form("channelId", channelId)
				.form("maxResult",rowMax)
				.form("page",page)
				.form("needHtml",1)
				.form("needContent",1)
				.form("needAllList",1)
				.header("Authorization", "APPCODE " + appCode)
				.execute().body();
		JSONObject obj = JSONObject.parseObject(body);
		log.debug(JSON.toJSONString(obj,true));
		if(obj.getIntValue("showapi_res_code")==0) {
			obj=obj.getJSONObject("showapi_res_body").getJSONObject("pagebean");
			log.debug(JSON.toJSONString(obj,true));
			JSONArray arr = obj.getJSONArray("contentlist");
			log.debug(JSON.toJSONString(arr,true));
			for(int i=0;i<arr.size();i++) {
				obj = arr.getJSONObject(i);
				log.debug(JSON.toJSONString(obj,true));
				News news = new News();
				list.add(news);
				news.setChannelId(obj.getString("channelId"));
				news.setContent(obj.getString("html"));
				news.setDesc(obj.getString("desc"));
				news.setId(obj.getString("id"));
				List<String> images = new ArrayList<String>();
				news.setImages(images);
				JSONArray imgs = obj.getJSONArray("imageurls");
				for(int j=0;j<imgs.size() && j<3;j++) {
					try {
						images.add(imgs.getJSONObject(j).getString("url"));
					}catch (Exception e) {
						log.warn("获取图片错误",e);
					}
				}
				news.setLink(obj.getString("link"));
				try {
					news.setTime(format.parse(obj.getString("pubDate")));
				}catch (Exception e) {
					news.setTime(new Date());
				}
				news.setTitle(obj.getString("title"));
				news.setWorker(obj.getString("source")); 
			}
			
		}else {
			String msg = obj.getString("showapi_res_error");
			log.warn(msg);
			throw new RuntimeException(msg);
		}
		return list;
	}

	/**
	 * <pre>
	 * TODO : 新闻类别
	 * ClassName : com.teach.commons.NewsClass
	 * Author : J.L.Zhou
	 * Date : 2020-07-02 11:11
	 * Version : V1.0
	 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
	 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes</pre>
	 */
	public static class NewsClass {
		/**
		 * - 频道id
		 */
		private String channelId;
		/**
		 * - 频道名称
		 */
		private String name;

		public String getChannelId() {
			return channelId;
		}

		public void setChannelId(String channelId) {
			this.channelId = channelId;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}
	
	/**
	 * <pre>
	 * TODO : 新闻
	 * ClassName : com.teach.commons.News
	 * Author : J.L.Zhou
	 * Date : 2020-07-02 11:12
	 * Version : V1.0
	 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
	 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes</pre>
	 */
	public static class News {
		/**
		 * - 新闻编号
		 */
		private String id;
		
		/**
		 * - 原地址
		 */
		private String link;
		/**
		 * - 新闻频道编号
		 */
		private String channelId;
		/**
		 * - 新闻标题
		 */
		private String title;
		/**
		 * - 新闻简介
		 */
		private String desc;
		/**
		 * - 新闻内容
		 */
		private String content;
		/**
		 * - 新闻作者
		 */
		private String worker;
		/**
		 * - 新闻事件
		 */
		private Date time;
		
		/**
		 * - 新闻图片
		 */
		private List<String> images;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getChannelId() {
			return channelId;
		}

		public void setChannelId(String channelId) {
			this.channelId = channelId;
		}

		public String getTitle() {
			return title;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public String getDesc() {
			return desc;
		}

		public void setDesc(String desc) {
			this.desc = desc;
		}

		public String getContent() {
			return content;
		}

		public void setContent(String content) {
			this.content = content;
		}

		public String getWorker() {
			return worker;
		}

		public void setWorker(String worker) {
			this.worker = worker;
		}

		public Date getTime() {
			return time;
		}

		public void setTime(Date time) {
			this.time = time;
		}

		public List<String> getImages() {
			return images;
		}

		public void setImages(List<String> images) {
			this.images = images;
		}

		public String getLink() {
			return link;
		}

		public void setLink(String link) {
			this.link = link;
		}
		
		
	}
	
	
	
	
	public static void main(String[] args) {
//		log.info(JSON.toJSONString(spider.listNewsClass(),true));
		log.info(JSON.toJSONString(spider.listNews("", 2, 1),true));
	}

}
